mod config;
mod error;
mod models;
mod db;
mod services;
mod routes;
mod scheduler;
mod utils;
mod api_doc;

use std::sync::Arc;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, fmt::time::OffsetTime};
use time::macros::offset;


#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // 初始化日志（使用中国时区 UTC+8）
    let timer = OffsetTime::new(
        offset!(+8),
        time::format_description::well_known::Rfc3339,
    );
    
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "info,simple_server=debug".into()),
        )
        .with(tracing_subscriber::fmt::layer().with_timer(timer))
        .init();

    tracing::info!("Starting RemindMe Server...");

    // 加载配置
    let config = config::Config::load()?;
    tracing::info!("Configuration loaded successfully");
    tracing::info!("Server will run on {}:{}", config.server_host, config.server_port);

    // 初始化数据库
    let pool = db::init_database(&config.database_url).await?;
    tracing::info!("Database initialized successfully");

    // 创建应用状态
    let config_arc = Arc::new(config.clone());
    let msg_cache = utils::MessageCache::new(300); // 5分钟过期
    let scheduler_cache = msg_cache.clone(); // 为 scheduler 克隆一份
    let app_state = routes::AppState {
        pool: pool.clone(),
        config: config_arc.clone(),
        msg_cache,
    };

    // 创建路由
    let app = routes::create_router(app_state);

    // 启动定时任务调度器
    tokio::spawn(async move {
        if let Err(e) = scheduler::start_reminder_scheduler(pool, config.clone(), scheduler_cache).await {
            tracing::error!("Failed to start scheduler: {}", e);
        }
    });

    // 启动服务器
    let addr = format!("{}:{}", config_arc.server_host, config_arc.server_port);
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    tracing::info!("Server listening on {}", addr);

    axum::serve(listener, app).await?;

    Ok(())
}
